package jam.network.message;

import jam.model.*;
import jam.network.*;
import java.util.*;

//
// =============================================================================
//

public class ClientActionJoin extends ClientCommand {
    protected static final String KEYWORD = "CA_JOIN";
    private String channelName;
    
    //
    // =========================================================================
    //
    
    /**
     */
    @Override
    public void process(ClientController controller) {
        NetworkController network = controller.getNetworkController();
        ClientModel client = controller.getModel();
        ServerModel server = network.getModel();
        String username = client.getUser().getUsername();
        
        // Create a channel if it doesn't already exist.
        Channel channel = server.getChannel(this.channelName);
        if (channel == null)
            channel = new Channel(this.channelName);
 
        // Make sure we're actually allowed in the channel
        if (channel.isLocked() && channel.hasInvited(username) == false) {
            controller.send(new ServerResponse(this, false));
            return;
        } else {
            channel.removeInvited(username);
        }
                       
        // Update the releveant lists.
        channel.addUser(username);
        server.addChannel(channel);
        client.addChannel(channel);                            
        
        // Alert all users in the channel, except us.
        Set<String> users = channel.getUsers();
        synchronized(users) {
	        for (String user: users) {
	            if (user.equalsIgnoreCase(username))
	                continue;
	                
	            ClientController userController = server.getLoggedInMap().get(user);
	            userController.send(new ServerActionJoin(
	                userController.getNextTransactionId(),
	                this.channelName,
	                username));
	        } 
        }
        
        // Respond to the first client.
        controller.send(new ServerResponse(this, true));
    }
    
    //
    // =========================================================================
    //
    
    @Override
    protected String getKeyword() { return ClientActionJoin.KEYWORD; }
    
    //
    // =========================================================================
    //
    
    /**
     * Constructor. Processes the data string.
     *
     * @param transactionId The identification number for this particular message.
     * @param args A scanner with the arguments
     */
    protected ClientActionJoin (int transactionId, Scanner args) {
        super(transactionId);
        
        // Read in the message arguments.
        this.channelName = args.next();
    }
}